package service

import (
	"encoding/json"
	"github.com/gogf/gf/encoding/gjson"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/util/gconv"
	"github.com/zhang201702/zhang/zlog"
)

type CertService struct {
	BaseService
	CertTextService Service
}

func init() {
	registerService("cert", func(name string) Service {
		return &CertService{
			BaseService:     newBaseService(name),
			CertTextService: NewService("cert_text"),
		}
	})
}
func (service *CertService) Fetch(id string) (result g.Map, err error) {
	result, err = service.Dao.Fetch(id)
	if err == nil {
		list, err2 := service.CertTextService.List(g.Map{"certId": id})
		if err2 == nil {
			result["items"] = list
		}
		for i := range list {
			item := list[i]
			options := gconv.String(item["options"])
			if options != "" {
				json, _ := gjson.DecodeToJson(options)
				item["options"] = json
			} else {
				item["options"] = g.Map{}
			}
		}
	}

	return result, err
}

func (service *CertService) Save(data g.Map) (result interface{}, err error) {
	items := data["items"]
	delete(data, "items")
	id := gconv.String(data["id"])
	if id != "" {
		result0, _ := service.Dao.Fetch(id)
		if result0 == nil {
			result, err = service.Dao.Insert(data)
		} else {
			result, err = service.Dao.Save(data)
		}
	} else {
		result, err = service.Dao.Save(data)
	}
	if err == nil {
		id := gconv.String(data["id"])
		if id != "" {
			service.CertTextService.DeleteAll(g.Map{"certId": data["id"]})
		}
		items := gconv.Maps(items)
		for i := range items {
			item := items[i]
			item["certId"] = id
			if options, ok := item["options"]; ok {
				ob, err := json.Marshal(options)
				if err != nil {
					zlog.Error(err, "证书明细添加失败", item)
					continue
				}
				item["options"] = string(ob)
			} else {
				item["options"] = "{}"
			}
			_, er2 := service.CertTextService.Insert(item)
			if er2 != nil {
				zlog.Error(er2, "添加证书明细异常", item)
			}
		}
		data["items"] = items
	}
	return data, err
}

func (service *CertService) Delete(id string) (result interface{}, err error) {
	result, err = service.Dao.Delete(id)
	if err == nil {
		service.CertTextService.DeleteAll(g.Map{"certId": id})
	}
	return result, err
}
